package com.t3go.t3_map.business.common;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.shareware.common.ApplicationKt;
import com.shareware.common.utils.LogExtKt;
import com.t3go.passenger.base.utils.FIvLoader;
import com.t3go.passenger.base.utils.JsonUtils;
import com.t3go.passenger.base.utils.ViewUtils;
import com.t3go.t3_map.R;
import com.t3go.t3_map.entity.Annotation;
import com.t3go.t3_map.entity.LabelAttrs;
import com.t3go.t3_map.entity.LabelInfo;
import com.t3go.t3_map.entity.PinArgs;
import com.t3go.t3_map.utils.MapFoundation;
import com.t3go.t3_map.views.T3StrokeTextView;
import com.t3map.api.map.T3Map;
import com.t3map.api.map.T3Projection;
import com.t3map.api.map.model.T3LatLng;
import com.t3map.api.map.model.T3Marker;
import com.t3map.api.map.model.T3MarkerOptions;
import com.t3map.api.map.model.T3Polyline;
import com.t3map.api.map.utils.T3MapUtils;


public class CommonMapHelper extends MapHelper {

    private static final String TAG = "CommonMapHelper";

    public CommonMapHelper(Context context, T3Map map) {
        super(context, map);
    }

    public T3Marker addPinMarker(Annotation data) {
        if (mMap == null || data == null || data.getArgs() == null) {
            return null;
        }
        PinArgs args = JsonUtils.fromJson(JsonUtils.toJson(data.getArgs()), PinArgs.class);
        if (args == null || args.getImage() == null) {
            return null;
        }

        View view = buildMarkerView(getMarkerName(args), getMarkerIcon(args));
        ImageView pointImage = view.findViewById(R.id.iv_personal_dot);
        float[] anchors = MapFoundation.calcAnchor(MapFoundation.convertViewToBitmap(view), pointImage);
        T3MarkerOptions t3MarkerOptions = new T3MarkerOptions(new T3LatLng(data.getLatitude(), data.getLongitude()))
                .iconView(view)
                .anchor(anchors[0], anchors[1])
                .draggable(false)
                .zIndex(data.getzIndex());
        return mMap.addMarker(t3MarkerOptions);
    }

    public void updatePinMarker(T3Marker marker, Annotation data) {
        if (mMap == null || marker == null || data == null || data.getArgs() == null) {
            return;
        }
        PinArgs args = JsonUtils.fromJson(JsonUtils.toJson(data.getArgs()), PinArgs.class);
        if (args == null || args.getImage() == null) {
            return;
        }
        View view = buildMarkerView(getMarkerName(args), getMarkerIcon(args));
        ImageView pointImage = view.findViewById(R.id.iv_personal_dot);
        float[] anchors = MapFoundation.calcAnchor(MapFoundation.convertViewToBitmap(view), pointImage);

        marker.setPosition(new T3LatLng(data.getLatitude(), data.getLongitude()));
        marker.setView(view);
        marker.setAnchor(anchors[0], anchors[1]);
    }

    private String getMarkerName(PinArgs args) {
        if (args != null && args.getText() != null) {
            return args.getText().getText();
        }
        return null;
    }

    private String getMarkerIcon(PinArgs args) {
        if (args != null && args.getImage() != null) {
            return args.getImage().getImageName();
        }
        return null;
    }

    private View buildMarkerView(String content, String resId) {
        ViewGroup view = (ViewGroup) LayoutInflater.from(ApplicationKt.getContextGlobal()).inflate(R.layout.map_marker_personal_spot_right, null);
        ImageView ivPoint = view.findViewById(R.id.iv_personal_dot);
        T3StrokeTextView tvName = view.findViewById(R.id.tv_personal_name);
        View flPersonalTag = view.findViewById(R.id.fl_personal_tag);
        flPersonalTag.setVisibility(View.GONE);
        tvName.setText(content);
        tvName.setStrokeWidth(10);
        tvName.setStrokeColor(Color.WHITE);
        ivPoint.setBackground(null);
        FIvLoader.get().load(ivPoint, resId);
        return view;
    }

    /**
     * 绘制选中路线标签
     */
    public T3Marker drawLabel(LabelInfo labelInfo, T3Polyline polyline, T3LatLng start, T3LatLng end) {

        //起终点没有获取到的时候不进行标签绘制
        if (start == null || end == null) {
            return null;
        }

        // 计算地图显示中心点
        Point center = calcMapCenter(start, end);
        if (center == null) {
            return null;
        }

        //获取偏移后中心点经纬度
        T3LatLng centerLatLng = fromScreenLocation(center);

        //路线上离中心点最近坐标，及label背景图片
        LabelAttrs attrs = getLabelEntity(polyline, centerLatLng);

        //渲染标签
        T3MarkerOptions options = buildLabelOptions(attrs, labelInfo);
        if (options == null) {
            return null;
        }

        if (mMap != null) {
            return mMap.addMarker(options);
        }

        return null;
    }

    private Point calcMapCenter(T3LatLng start, T3LatLng end) {
        if (start == null || end == null || mMap == null) {
            return null;
        }
        T3Projection projection = mMap.getProjection();
        if (projection == null) {
            return null;
        }
        Point startPoint = projection.toScreenLocation(start);
        Point endPoint = projection.toScreenLocation(end);
        // 根据中心点的位置 计算的偏移后 地图中心的坐标
        return new Point((startPoint.x + endPoint.x) / 2, (startPoint.y + endPoint.y) / 2 - 60);
    }

    /**
     * 根据选中的线路及屏幕中心点来确认路线标签显示位置、偏移量、背景
     */
    private LabelAttrs getLabelEntity(T3Polyline polyline, T3LatLng centerLatLng) {
        LogExtKt.log(TAG, "updateLabelMarkerPosition");

        if (polyline == null || centerLatLng == null) {
            return null;
        }

        LabelAttrs data = new LabelAttrs();

        //获取路径距离中心点最近坐标作为label坐标
        T3LatLng position = polyline.getNearestLatLng(centerLatLng);

        data.setPosition(position);

        //计算label坐标与中心点坐标角度
        float labelAngle = T3MapUtils.calculateBearing(centerLatLng, position);

        //根据角度绘制labelView，以及偏移量。
        if (0 <= labelAngle && labelAngle < 90) {
            //右上角
            data.setAnchorX(1);
            data.setAnchorY(0);
            data.setBgResId(R.drawable.route_label_bg_right_top);
        } else if (90 <= labelAngle && labelAngle < 180) {
            //右下角
            data.setAnchorX(1);
            data.setAnchorY(1);
            data.setBgResId(R.drawable.route_label_bg_right_bottom);
        } else if (180 <= labelAngle && labelAngle < 270) {
            //左下角
            data.setAnchorX(0);
            data.setAnchorY(1);
            data.setBgResId(R.drawable.route_label_bg_left_bottom);
        } else {
            //左上角
            data.setAnchorX(0);
            data.setAnchorY(0);
            data.setBgResId(R.drawable.route_label_bg_left_top);
        }
        return data;
    }

    private T3MarkerOptions buildLabelOptions(LabelAttrs attrs, LabelInfo label) {
        if (attrs == null || attrs.getPosition() == null || label == null) {
            return null;
        }
        View labelView = buildRouteLabelView(attrs.getBgResId(), label);
        return new T3MarkerOptions(attrs.getPosition())
                .anchor(attrs.getAnchorX(), attrs.getAnchorY())
                .zIndex(5)
                .iconView(labelView);
    }

    public static View buildRouteLabelView(int bgResource, @NonNull LabelInfo data) {
        View viewPop = LayoutInflater.from(ApplicationKt.getContextGlobal()).inflate(R.layout.view_route_label, null);
        ViewGroup rootV = viewPop.findViewById(R.id.ll_root);
        TextView titleTv = viewPop.findViewById(R.id.tv_label_title);
        View dividerV = viewPop.findViewById(R.id.v_split_divider);
        TextView distanceTv = viewPop.findViewById(R.id.tv_label_distance);
        TextView timeTv = viewPop.findViewById(R.id.tv_label_time);
        TextView tipText = viewPop.findViewById(R.id.text_tip);
        //设置背景图片
        if (bgResource != 0) {
            LogExtKt.log("TAG", "getRouteLabelView bgResource=" + bgResource);
            rootV.setBackgroundResource(bgResource);
        }
        if (TextUtils.isEmpty(data.getTitle())) {
            titleTv.setVisibility(View.GONE);
            dividerV.setVisibility(View.GONE);
        } else {
            titleTv.setVisibility(View.VISIBLE);
            dividerV.setVisibility(View.VISIBLE);
        }
        //设置分割线透明度
        ViewUtils.setAlpha(dividerV, 0.4f);
        //设置标签内容
        titleTv.setText(data.getTitle());
        //设置预计距离
        distanceTv.setText(data.getDistance());
        //设置预计时间
        timeTv.setText(data.getTime());

        if (!TextUtils.isEmpty(data.getSubTitle())) {
            tipText.setVisibility(View.VISIBLE);
            tipText.setText(data.getSubTitle());
        } else {
            tipText.setVisibility(View.GONE);
        }

        return viewPop;
    }

    private T3LatLng fromScreenLocation(Point point) {
        if (mMap != null && mMap.getProjection() != null) {
            return mMap.getProjection().fromScreenLocation(point);
        }
        return null;
    }

}
